<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class TaskRecordItem extends AdminController
{
    public $_validation = null;

    function __construct()
    {
        parent::__construct();
        $this->load->model('MTaskRecordItem');

        $this->_validation = Array(
            array('field' => 'record_id', 'label' => '所属测评记录', 'rules' => 'required|integer|max_length[11]')
        , array('field' => 'pay_request_id', 'label' => '所属财务申请记录', 'rules' => 'integer|max_length[11]')
        , array('field' => 'finace_id', 'label' => '财务打款人', 'rules' => 'integer|max_length[11]')
        , array('field' => 'payment_type', 'label' => '付款类型', 'rules' => 'required|integer')
        , array('field' => 'pay_method', 'label' => '付款方式', 'rules' => 'trim|integer|max_length[4]')
        , array('field' => 'contact', 'label' => '联系方式', 'rules' => 'trim|max_length[255]')
        , array('field' => 'pay_account', 'label' => '接收付款的账号', 'rules' => 'trim|max_length[255]')
        , array('field' => 'amount', 'label' => '付款金额', 'rules' => 'numeric')
        , array('field' => 'coin_type', 'label' => '接收款币种', 'rules' => 'trim|integer|max_length[4]')
        , array('field' => 'rate_rmb', 'label' => '对人民币汇率', 'rules' => 'numeric')
        , array('field' => 'status', 'label' => '状态', 'rules' => 'integer')
        , array('field' => 'remark', 'label' => '备注', 'rules' => '')
        , array('field' => 'update_time', 'label' => '更新时间', 'rules' => '')
        );
        $this->load->model('MAdmin');
        $this->load->model('MAdminGroup');
        $this->load->model('MShop');
        $allReviewsAdmin = $this->MAdmin->getAllReviewsAdmin();//所有测评人,包含销售组成员，也可以作为测试人
        $allSaleGroups = MAdminGroup::getAllGroupsByType(1);//所有销售组
        $allReviewsGroups = MAdminGroup::getAllGroupsByType(2);//所有测评组
        $allShops = $this->MShop->getAllShopsTrue();
        $allFanaceAdmin = $this->MAdmin->getAllFanceAdmin();//所有财务人员
        $this->assign('allReviewsAdmin', $allReviewsAdmin);
        $this->assign('allSaleGroups', $allSaleGroups);
        $this->assign('allReviewsGroups', $allReviewsGroups);
        $this->assign('allShops', $allShops);
        $this->assign('allFanaceAdmin', $allFanaceAdmin);
    }

    function index()
    {
        //$this->output->enable_profiler(TRUE);
        $this->load->library('FormFilter');
        $this->load->helper('formfilter');
        $this->formfilter->addFilter('record.task_id', 'where');
        $this->formfilter->addFilter('record.operator_id', 'where');
        $this->formfilter->addFilter('t.country', 'where');
        $this->formfilter->addFilter('t.group_id', 'where');
        $this->formfilter->addFilter('t.shop_id', 'where');
        $this->formfilter->addFilter('item.contact', 'where');
        $this->formfilter->addFilter('record.order_no', 'where');
        $this->formfilter->addFilter('item.status', 'where');
        $this->formfilter->addFilter('item.payment_type', 'where');
        $this->formfilter->addFilter('item.pay_method', 'where');

        if ($begintime = filterValue('task_record_item_create_time_begin')) {
            $this->formfilter->addFilter('task_record_item_create_time_begin', 'where', array('item.create_time >= ', strtotime($begintime . ' 00:00:00')));
        }
        if ($endtime = filterValue('task_record_item_create_time_end')) {
            $this->formfilter->addFilter('task_record_item_create_time_end', 'where', array('item.create_time <= ', strtotime($endtime . ' 23:59:59')));
        }

        if ($begintime = filterValue('task_record_item_update_time_begin')) {
            $this->formfilter->addFilter('task_record_item_update_time_begin', 'where', array('item.update_time >= ', strtotime($begintime . ' 00:00:00')));
        }
        if ($endtime = filterValue('task_record_item_update_time_end')) {
            $this->formfilter->addFilter('task_record_item_update_time_end', 'where', array('item.update_time <= ', strtotime($endtime . ' 23:59:59')));
        }

        $number_perpage = filterValue('taskrecorditem_number_perpage');
        $total_number = $this->MTaskRecordItem->getCount();
        $limit = $this->pagination($total_number, '', $number_perpage);
        $list = $this->MTaskRecordItem->getList($limit);
        $this->assign('total_number', $total_number);
        $this->assign('list', $list);
        $this->layout();
    }

    function add($task_id){
        show_error('添加请到录入任务处填写单号进行添加');
    }

    function edit($id)
    {
        show_error('修改请到录入任务处填写单号进行修改');
    }

    function delete($id, $update_time)
    {
        if (!is_numeric($id) || !is_numeric($update_time)) {
            show_error(l('id_not_null'));
        }
        if (!$this->MTaskOperate->delete($id, $update_time)) {
            errorAndRedirect(l('data_fail'));
        }
        successAndRedirect(l('delete_success'));
    }

    /**
     * ajax 添加指定任务id的任务操作数据
     * @param $id
     */
    function ajaxAddTaskOperate($task_id)
    {
        if (!$this->p->add) {
            //权限不足
            model_error(l('user_has_nopower'));
        }
        if (((int)$task_id) . '' !== $task_id) {
            model_error(l('id_or_updated_not_null'));
        }
        $this->load->model('MTask');
        if (!$task = $this->MTask->getById((int)$task_id)) {
            model_error('当前任务不存在！');
        }

        $obj = $this->MTaskOperate->createVo();
        $this->load->library('form_validation');
        $this->form_validation->set_rules($this->_validation);

        if ($this->form_validation->run() == TRUE) {
            $this->load->helper('populate');
            $newObj = populate((Object)((Array)$obj), $this->form_validation->post());
            //检查是否为新客户：客户联系方式在以往测评操作记录中已经存在过算老用户，否则为新用户
            $findObj = $this->MTaskOperate->getOne(array('contact' => $newObj->contact));
            if ($findObj) {
                $newObj->is_new = 2;
            } else {
                $newObj->is_new = 1;
            }
            $newObj->order_time = strtotime($newObj->order_time);
            $newObj->pay_time = strtotime($newObj->pay_time);
            //事务添加任务操作，并修改任务表状态为已接
            $this->db->trans_start();
            if (!$this->MTaskOperate->add($newObj)) {
                $this->db->_trans_status = FALSE;
            }

            if ($task->status == MTask::STATE_NOT_ACCEPT) {
                $task->status = MTask::STATE_ACCEPTED;
                if (!$this->MTask->update($task)) {
                    $this->db->_trans_status = FALSE;
                }
            }

            $this->db->trans_complete();
            if ($this->db->trans_status() !== FALSE) {
                model_success('添加任务操作成功！');
            } else {
                model_error('添加任务操作失败！');
            }
        }

        $this->assign('obj', $obj);
        $this->assign('task', $task);
        $this->assign('thisControllerName', '添加任务操作记录');
        $this->assign('action', 'add');
        $this->layout_modal('modal-form');
    }

    /**
     * ajax 修改指定任务id的任务操作数据
     * @param unknown $id
     */
    function ajaxEditTaskOperate($task_record_item_id)
    {
        if (!$this->p->add) {
            //权限不足
            model_error(l('user_has_nopower'));
        }
        if (!is_numeric($task_record_item_id)) {
            show_error(l('id_not_null'));
        }
        $obj = $this->MTaskOperate->getOne(Array('id' => $task_record_item_id));
        if (!$obj) {
            model_error('未找到定义！');
        }
        $this->load->model('MTask');
        if (!$task = $this->MTask->getById((int)$obj->task_id)) {
            model_error('当前任务不存在！');
        }
        $this->editObj = $obj;

        $this->load->library('form_validation');
        $this->form_validation->set_rules($this->_validation);

        if ($this->form_validation->run() == TRUE) {
            $this->load->helper('populate');
            $newObj = populate((Object)((Array)$obj), $this->form_validation->post());
            //检查是否为新客户：客户联系方式在以往测评操作记录中已经存在过算老用户，否则为新用户
            $findObj = $this->MTaskOperate->getOne(array('contact' => $newObj->contact));
            if ($findObj) {
                $newObj->is_new = 2;
            } else {
                $newObj->is_new = 1;
            }
            $newObj->order_time = strtotime($newObj->order_time);
            $newObj->pay_time = strtotime($newObj->pay_time);

            //事务添加任务操作，并修改任务表状态为已接
            if (!$this->MTaskOperate->update($newObj)) {
                $this->db->_trans_status = FALSE;
            }
            $task->status = MTask::STATE_ACCEPTED;
            if (!$this->MTask->update($task)) {
                $this->db->_trans_status = FALSE;
            }
            $this->db->trans_complete();
            if ($this->db->trans_status() !== FALSE) {
                model_success('修改任务操作成功！');
            } else {
                model_error('修改任务操作失败！');
            }
        }

        $this->assign('obj', $obj);
        $this->assign('task', $task);
        $this->assign('thisControllerName', '修改任务操作记录');
        $this->assign('action', 'edit');
        $this->layout_modal('modal-form');
    }

    /**
     * ajax 查找给定id的任务操作详情
     * @param $id
     */
    function ajaxViewDetail($id)
    {
        if (((int)$id) . '' !== $id) {
            model_error(l('id_or_updated_not_null'));
        }
        //item信息
        if (!$obj = $this->MTaskRecordItem->getById((int)$id)) {
            model_error('记录款项不存在！');
        }
        //item对应record信息
        $this->load->model('MTaskRecords');
        if(!$record = $this->MTaskRecords->getById((int)$obj->record_id)){
            model_error('任务操作记录不存在！');
        }
        //对应task信息
        $this->load->model('MTask');
        if(!$task = $this->MTask->getById((int)$record->task_id)){
            model_error('对应任务不存在！');
        }

        if (($postStatus = $this->input->post('status')) != null) {
            if (!($this->_user->role_id == 7 || $this->_user->role_id == 8)) {
                model_error('只有财务处理者才可以修改任务操作记录状态！');
            }
            $obj->status = $postStatus;
            $obj->finance_id = $this->_user->id;
            $obj->remark = $this->input->post('remark');

            if ($this->input->post('add_image_' . $id)) {
                $record->add_image = $this->input->post('add_image_' . $id);
            }
            if ($this->input->post('add_image_1_' . $id)) {
                $record->add_image_1 = $this->input->post('add_image_1_' . $id);
            }
            if ($this->input->post('add_image_2_' . $id)) {
                $record->add_image_2 = $this->input->post('add_image_2_' . $id);
            }

            //事务处理
            $this->db->trans_start();
            if (!$this->MTaskRecordItem->update($obj)) {
                $this->db->_trans_status = FALSE;
            }
            if (!$this->MTaskRecords->update($record)) {
                $this->db->_trans_status = FALSE;
            }
            $this->db->trans_complete();
            if ($this->db->trans_status() !== FALSE) {
                model_success('更新任务操作状态成功！');
            } else {
                model_error('更新任务操作状态失败！');
            }
        }

        $this->assign('obj', $obj);
        $this->assign('record', $record);
        $this->assign('task', $task);
        $this->assign('thisControllerName', '测评记录款项详情');
        $this->layout_modal('modal-detail');
    }

    /**
     * ajax 请求给定order_no的所有测评记录
     */
    public function ajaxReturnRecordsByOrderNo()
    {
        $this->load->model('MTaskOperate');
        $task_id = $this->input->post('task_id');
        $order_no = $this->input->post('order_no');
        $current_id = $this->input->post('current_id');
        if ($task_id) {   //确定同一任务的情况
            if ($current_id) {
                $allTaskOperates = $this->MTaskOperate->getAll(array('task_id' => $task_id, 'order_no' => $order_no, 'id <> ' => $current_id, 'status <>' => 4)); //edit情况
            } else {
                $allTaskOperates = $this->MTaskOperate->getAll(array('task_id' => $task_id, 'order_no' => $order_no, 'status <>' => 4));   //add情况
            }
        } else {  //全局查找，非同一任务情况
            if ($current_id) {
                $allTaskOperates = $this->MTaskOperate->getAll(array('order_no' => $order_no, 'id <> ' => $current_id, 'status <>' => 4)); //edit情况
            } else {
                $allTaskOperates = $this->MTaskOperate->getAll(array('order_no' => $order_no, 'status <>' => 4));   //add情况
            }
        }

        exit(json_encode($allTaskOperates));
    }


    public function group_cepings(){
        $data = $this->input->post();
        $ceping_ids = $data['ceping_ids'];
        $cepings = $this->MTaskRecordItem->getAllByCepingId($ceping_ids);
        //根据测评记录状态判断是否可以合并打款
        $statuses = $cepings['statuses'];
        if (in_array(1, $statuses) || in_array(3, $statuses)) {
            exit(json_encode([
                'status' => 0,
                'msg' => '只有初始待提交状态的或财务标记不通过的款项才可以合并提交，请检查后重新提交！'
            ]));
        }
        //判断已经可以合并打款后，将ids保存到session中
        $this->session->set_userdata('PAY_REQUEST_CEPING_IDS', $ceping_ids);

        exit(json_encode([
            'status' => 1,
            'msg' => '合并成功',
        ]));
    }

    // 批量删除
    public function group_delete()
    {
        $this->load->model('MTaskRecords');
        $this->load->model('MTaskApplyNum');
        $this->load->model('MTask');
        $this->db->trans_start();
        $data = $this->input->post();
        $ceping_ids = $data['ceping_ids'];
        $cepings = $this->MTaskRecordItem->getAllByCepingIdDel($ceping_ids);
        //根据测评记录状态判断是否可以合并打款
        $kvArr = array();
        foreach ($cepings as $k => $v) {
            $kvArr['statuses'][] = $v->status;
        }
        $statuses = $kvArr['statuses'];
        if (in_array(1, $statuses) || in_array(3, $statuses)) {
            exit(json_encode([
                'status' => 0,
                'msg' => '只有初始待提交状态的或财务标记不通过的款项才可以删除！'
            ]));
        }

        //判断已经可以删除后，删除item
        $records_ids = array();
        foreach ($cepings as $c) {
            $records_ids[] = $c->record_id;
            if (!$this->MTaskRecordItem->delete($c->id, $c->update_time)) {
                $this->db->_trans_status = false;
            }
        }

        // 判断records下是否有item记录，无则删除此records
        foreach (array_unique($records_ids) as $r_id) {
            $item = $this->MTaskRecordItem->getOne(['record_id' =>  $r_id]);

            $record = $this->MTaskRecords->getOne(['id' =>  $r_id]);

            if (!$item) {
                if (!$this->MTaskRecords->delete($record->id, $record->update_time)) {
                    $this->db->_trans_status = false;
                }

                if ($this->MTaskApplyNum->updateCepingRecordsCount($record->task_id, $this->_user->id) === FALSE) {
                    $this->db->_trans_status = FALSE;
                }

                //更新task表中测评/销量数
                if ($this->MTask->updateCepingRecordsCount($record->task_id) === FALSE) {
                    $this->db->_trans_status = FALSE;
                }
            }
        }

        $this->db->trans_complete();
        if ($this->db->trans_status() !== false) {
            exit(json_encode([
                'status' => 1,
                'msg'    => '删除成功'
            ]));
        } else {
            exit(json_encode([
                'status' => 0,
                'msg'    => '删除失败'
            ]));
        }
    }

    public function group_tasks(){
        $data = $this->input->post();
        $task_ids = $data['task_ids'];
        $num = $data['apply_number'];

        $this->db->trans_start();
        $this->load->model('MTaskApplyNum');
        foreach ($task_ids as $v){
            $this->load->model('MTask');
            $task = $this->MTask->getOne(['id' => $v]);
            if ($num > ($task->comment_need_num - $task->comment_applied_num)){
                continue;
            }else{
                $his = $this->MTaskApplyNum->getOne(['task_id' => $v,'operator_id' => $this->_user->id]);
                if ($his){
                    $his->apply_comment_num += $num;
                    if (!$this->MTaskApplyNum->update($his)){
                        $this->db->_trans_status = false;
                    }
                }else{
                    $obj = $this->MTaskApplyNum->createVo();
                    $obj->apply_comment_num = $num;
                    $obj->operator_id = $this->_user->id;
                    $obj->task_id = $v;
                    $obj->create_time = time();
                    $obj->update_time = time();

                    if (!$this->MTaskApplyNum->add($obj)){
                        $this->db->_trans_status = false;
                    }
                }

                $task->comment_applied_num += $num;
                if (!$this->MTask->update($task)){
                    $this->db->_trans_status = false;
                }
            }
        }

        if ($this->db->_trans_status){
            $this->db->trans_complete();
            exit(json_encode([
                'status' => 1,
                'msg' => '一键接单成功！',
            ]));
        }else{
            exit(json_encode([
                'status' => 0,
                'msg' => '一键接单失败！',
            ]));
        }
    }

    public function ajaxEdit(){
        $data = $this->input->post();
        $this->load->model('MTaskRecordItem');
        $item = $this->MTaskRecordItem->getById($data['id']);
        if ($item){
            if ($data['type'] == 'rate'){
                $item->rate_rmb = $data['value'];
            }else{
                $item->amount = $data['value'];
            }
            if ($this->MTaskRecordItem->update($item, $item->update_time)){
                exit(json_encode([
                    'status' => 1,
                    'msg'    => '修改成功'
                ]));
            }else{
                exit(json_encode([
                    'status' => 0,
                    'msg'    => '修改失败'
                ]));
            }
        }else{
            exit(json_encode([
                'status' => 0,
                'msg'    => '未定义的测评记录'
            ]));
        }
    }

    //批量标记传来的测评记录id为标定异常
    function setStatus2(){
        $ceping_ids = $this->input->post();
        $ceping_ids_str = implode(',',$ceping_ids['ceping_ids']);
        if($this->db->query('update `core_task_record_item` set `status`=2 where id in ('.$ceping_ids_str.')')){
            echo "批量标定‘不通过’操作成功";
        }else{
            echo "批量标定‘不通过’操作失败";
        }
    }
    //批量标记传来的测评记录id为标定异常

    function setStatus3(){
        $ceping_ids = $this->input->post();
        $ceping_ids_str = implode(',',$ceping_ids['ceping_ids']);
        if($this->db->query('update `core_task_record_item` set `status`=3 where id in ('.$ceping_ids_str.')')){
            echo "批量标定‘通过’操作成功";
        }else{
            echo "批量标定‘通过’操作失败";
        }
    }
}
